package com.flycms.modules.visit.controller;

import com.flycms.common.controller.BaseController;
import com.flycms.common.utils.web.AgentUtils;
import com.flycms.common.utils.web.Servlets;
import com.flycms.common.utils.StringUtils;
import com.flycms.modules.shiro.ShiroUtils;
import com.flycms.modules.visit.entity.Visit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * @author 孙开飞
 * @version 1.0 <br/>
 * @Description: 添加用户访问统计
 * @email 79678111@qq.com
 * @Date: 15:08 2019/11/18
 */
@Controller
public class VisitController extends BaseController {
    @RequestMapping("/visit_log${url.suffix}")
    public void visitLog(@RequestParam(value = "siteId", required = false) String siteId,HttpServletRequest request, HttpServletResponse response) {
        String agent = request.getHeader("User-Agent") == null ? "": request.getHeader("User-Agent");
        Visit visit =new Visit();

        String url = Servlets.getParam(request, "url");
        String referrer = Servlets.getParam(request, "referrer");
        String userAgent = request.getHeader("user-agent");
        visit.setSiteId(Long.parseLong(siteId));
        visit.setUserId(ShiroUtils.getLoginUser().getId());
        // 不超过最大长度
        visit.setCurrentUrl(StringUtils.substring(url, 0, 255));
        visit.setSourceReferrer(StringUtils.substring(referrer, 0, 255));
        visit.setVisitUserAgent(StringUtils.substring(userAgent, 0, 450));
        visit.setVisitOs(AgentUtils.getClientOS(agent));
        visit.setVisitIp(Servlets.getRemoteAddr(request));
        visitService.addVisit(visit);
    }

}
